package org.wwx.register;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;

import java.util.Properties;

/**
 * @date 2025/6/5
 * @author王闻薪
 */
public class NacosRegister {
    private static final String SERVER_ADDR = "127.0.0.1:8848";
    private static NamingService namingService;

    static {
        try {
            Properties properties = new Properties();
            properties.put("serverAddr", SERVER_ADDR);
            namingService = NamingFactory.createNamingService(properties);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    public static void register(String serviceName, String host, int port) {
        try {
            namingService.registerInstance(serviceName, host, port);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    public static String discover(String serviceName) {
        try {
            return namingService.selectOneHealthyInstance(serviceName).getIp() + ":"
                    + namingService.selectOneHealthyInstance(serviceName).getPort();
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }
}